package com.zs.demo;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @Author: Zhangshuqing
 * @Description:
 * @Date: Created in 16:38 2018/4/11
 * @Modified By:
 */
public class Client {

    public void  withClient() throws IOException {
        SocketChannel clientChannel=SocketChannel.open();
        clientChannel.connect(new InetSocketAddress("localhost",9099));
        ByteBuffer buffer=ByteBuffer.allocate(1024);
        if(clientChannel.finishConnect()){
            //发送
            ByteBuffer outBuffer=ByteBuffer.allocate(1024);
            outBuffer.put("hahah".getBytes());
            outBuffer.flip();
            clientChannel.write(outBuffer);
            //
            int len=clientChannel.read(buffer);
            int i=0;
            while (len!=-1){
                buffer.flip();
                while (buffer.hasRemaining()){
                    //Returns the number of elements between the current position and the limit.
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes, 0, bytes.length);
                    System.out.print(new String(bytes));
                }
                buffer.compact();
                len=clientChannel.read(buffer);
            }
        }

    }

    public static void main(String[] args) throws IOException {
        Client client=new Client();
        client.withClient();
    }
}
